#include "LabelList.h"
//necessary
#include <stdlib.h>
#include "utlist.h"
#include "memory-tools.h"
#include "string.h"

PlabelList initLabelList(){
	PlabelList result=mallocMemory(sizeof(LabelList),"LabelList.c:initLabelList:1");
	*result=NULL;
	return result;
}

//TODO testing for memory leak
void freeLabelList(PlabelList list){
	PlabelListElement element;
	PlabelListElement tmp;
	LL_FOREACH_SAFE(*list,element,tmp){
		LL_DELETE(*list,element);
	}
	freeMemory(sizeof(LabelList),list);
}

void printLabelList(FILE* f, PlabelList list){
	PlabelListElement element;
	fprintf(f,"{ ");
	LL_FOREACH(*list,element){
		printLabel(f,element->label);
		fprintf(f," ");
	}
	fprintf(f,"}");
}

void addLabelToLabelList(Plabel label,PlabelList list){
	PlabelListElement newelement=mallocMemory(sizeof(LabelListElement),"LabelList.c:addLabel:1");
	newelement->label=label;
	LL_APPEND(*list,newelement);
}

Plabel findLabelInLabelList(Plabel label, PlabelList list){
	PlabelListElement element;
	LL_FOREACH(*list,element){
		if (label->type!=element->label->type){
			continue;
		}
		if (strcmp(label->name,element->label->name)==0){
			return element->label;
		}
	}
	return NULL;
}

//TODO testing memory leak!
void removeLabelFromLabelList(Plabel label, PlabelList list){
	PlabelListElement element;
	PlabelListElement tmp;
	LL_FOREACH_SAFE(*list,element,tmp){
		if (label->type!=element->label->type){
			continue;
		}
		if (strcmp(label->name,element->label->name)==0){
			//we have to delete the element
			LL_DELETE(*list,element);
		}
	}
}

int getLabelListSize(PlabelList list){
	PlabelListElement tmp;
	int i;
	LL_COUNT(*list,tmp,i);
	return i;
}
